package it.unibz.ti2.internetPizzeria.servlets;

import it.unibz.ti2.internetPizzeria.dao.OrderDAO;
import it.unibz.ti2.internetPizzeria.dao.PropertyDAO;
import it.unibz.ti2.internetPizzeria.entities.Order;
import it.unibz.ti2.internetPizzeria.entities.Property;
import it.unibz.ti2.internetPizzeria.utils.RouteOptimizer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet responsible for reordering orders using RouteOptimizer class. Used by
 * "ordersReadyToDeliver.jsp" in AJAX's call.
 */
public class OptimalRoute extends HttpServlet {

	private static final long serialVersionUID = 8834260640854988051L;

	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		this.doPost(arg0, arg1);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		OrderDAO orderDAO = null;
		PropertyDAO propertyDAO = null;
		try {
			orderDAO = new OrderDAO();
			orderDAO.openSession();
			propertyDAO = new PropertyDAO();
			propertyDAO.openSession(orderDAO);
			String orderIdsParam = request.getParameter("orderIds");
			if (orderIdsParam != null && !orderIdsParam.equals("")) {
				List<Long> ids = new ArrayList<Long>();
				for (String orderIdText : orderIdsParam.split("#")) {
					if (!orderIdText.equals("")) {
						ids.add(Long.parseLong(orderIdText));
					}
				}
				List<Order> orders = orderDAO.getOrders(ids);

				float pizzeriaAddressLat = Float
						.parseFloat(propertyDAO.getProperty(
								Property.PizzeriaAddressLatKey).getValue());
				float pizzeriaAddressLng = Float
						.parseFloat(propertyDAO.getProperty(
								Property.PizzeriaAddressLngKey).getValue());

				orders = RouteOptimizer.optimize(pizzeriaAddressLat,
						pizzeriaAddressLng, orders);

				StringBuffer orderIdsResult = new StringBuffer();
				for (Order order : orders) {
					orderIdsResult.append(order.getId() + "#");
				}

				String result = orderIdsResult.toString();
				if (result.endsWith("#")) {
					result = result.substring(0, result.length() - 1);
				}
				response.setContentType("text/xml");
				response.getWriter().write(
						"<div id=\"result\">" + result + "</div>");
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (orderDAO != null) {
				orderDAO.closeSession();
			}
		}
	}
}
